package com.bawei.composeui2207a.day04.mvi.good

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.bawei.composeui2207a.day04.mvi.base.OnError
import com.bawei.composeui2207a.day04.mvi.base.OnLoading
import com.bawei.composeui2207a.day04.mvi.base.OnSuccess
import com.bawei.composeui2207a.model.GoodEntity
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/13 16:34
 * 功能：商品相关的页面
 */
@Composable
fun GoodPage(viewModel: GoodViewModel = hiltViewModel()) {

    // 1. 数据
    var list = remember {
        SnapshotStateList<GoodEntity.Result>()
    }
    LaunchedEffect(key1 = "") {
        launch {
            // 处理状态
            viewModel.uiState.collect {
                when (it) {
                    is OnError -> {}
                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        list.addAll((it.data as GoodEntity).result)
                    }
                }
            }
        }
        launch {
            // 发送意图
            viewModel.sendIntent(GoodIntent.FindGoodByKeyworld("鞋", 1, 10))
        }
    }

    // 2. 展示
    Column {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(70.dp)
        ) {
            Text(text = "维度商城", modifier = Modifier.align(Alignment.Center))
        }
        LazyColumn {

            items(list) {
                Row {
                    // 商品图片
                    AsyncImage(
                        modifier = Modifier.size(
                            110.dp
                        ), model = it.masterPic, contentDescription = null
                    )
                    // 商品名称与价格
                    Column {
                        Text(text = it.commodityName, maxLines = 1)
                        Text(text = "￥${it.price}", color = Color.Red)
                    }
                }
            }
        }
    }

}

@Preview
@Composable
fun GoodPagePreview() {
    GoodPage()
}

